import React, { useState, useEffect } from 'react'
import { Layout, Card, Row, Col, Space, Button, Typography, message, Spin } from 'antd'
import {
  HistoryOutlined,
  DiffOutlined,
  EyeOutlined,
  RollbackOutlined,
  PlusOutlined,
} from '@ant-design/icons'
import { useAppSelector, useAppDispatch } from '@/store'
import VersionHistory from './VersionHistory'
import VersionCompare from './VersionCompare'
import VersionDetail from './VersionDetail'
import { Version } from '@/types/version'
import * as versionAPI from '@/services/versionAPI'

const { Content, Sider } = Layout
const { Title } = Typography

interface VersionManagerProps {
  scriptId: string
  currentVersion?: Version | null
  onVersionChange?: (version: Version) => void
  showCreateVersion?: boolean
}

type ViewMode = 'history' | 'compare' | 'detail'

const VersionManager: React.FC<VersionManagerProps> = ({
  scriptId,
  currentVersion,
  onVersionChange,
  showCreateVersion = true,
}) => {
  const dispatch = useAppDispatch()
  const { theme } = useAppSelector(state => state.ui)
  
  // 状态管理
  const [versions, setVersions] = useState<Version[]>([])
  const [loading, setLoading] = useState(false)
  const [viewMode, setViewMode] = useState<ViewMode>('history')
  const [selectedVersion, setSelectedVersion] = useState<Version | null>(null)
  const [compareVersions, setCompareVersions] = useState<[Version, Version] | null>(null)
  const [siderCollapsed, setSiderCollapsed] = useState(false)

  // 加载版本历史
  const loadVersions = async () => {
    try {
      setLoading(true)
      const response = await versionAPI.getVersionHistory(scriptId)
      if (response.success && response.data) {
        setVersions(response.data.versions)
      }
    } catch (error) {
      console.error('加载版本历史失败:', error)
      message.error('加载版本历史失败')
    } finally {
      setLoading(false)
    }
  }

  // 处理版本选择
  const handleVersionSelect = (version: Version) => {
    setSelectedVersion(version)
    setViewMode('detail')
  }

  // 处理版本比较
  const handleVersionCompare = (version1: Version, version2: Version) => {
    setCompareVersions([version1, version2])
    setViewMode('compare')
  }

  // 交换比较版本
  const handleSwapCompareVersions = () => {
    if (compareVersions) {
      setCompareVersions([compareVersions[1], compareVersions[0]])
    }
  }

  // 处理版本回滚
  const handleVersionRevert = async (version: Version) => {
    try {
      const response = await versionAPI.revertToVersion(scriptId, version.id)
      if (response.success && response.data) {
        message.success(`已回滚到版本 v${version.version_number}`)
        onVersionChange?.(response.data)
        loadVersions() // 重新加载版本历史
      }
    } catch (error) {
      message.error('版本回滚失败')
    }
  }

  // 处理版本删除
  const handleVersionDelete = async (versionId: string) => {
    try {
      await versionAPI.deleteVersion(versionId)
      message.success('版本删除成功')
      loadVersions() // 重新加载版本历史
      
      // 如果删除的是当前查看的版本，返回历史视图
      if (selectedVersion?.id === versionId) {
        setSelectedVersion(null)
        setViewMode('history')
      }
    } catch (error) {
      message.error('版本删除失败')
    }
  }

  // 处理版本备注
  const handleVersionComment = async (versionId: string, comment: string) => {
    try {
      await versionAPI.updateVersionComment(versionId, comment)
      message.success('备注保存成功')
      loadVersions() // 重新加载版本历史
    } catch (error) {
      message.error('保存备注失败')
    }
  }

  // 创建新版本
  const handleCreateVersion = async () => {
    try {
      const response = await versionAPI.createVersion({
        script_id: scriptId,
        comment: '手动创建版本',
        is_major: false,
        created_by: '当前用户',
      })
      
      if (response.success && response.data) {
        message.success('新版本创建成功')
        onVersionChange?.(response.data)
        loadVersions()
      }
    } catch (error) {
      message.error('创建版本失败')
    }
  }

  // 返回历史视图
  const handleBackToHistory = () => {
    setViewMode('history')
    setSelectedVersion(null)
    setCompareVersions(null)
  }

  // 初始化
  useEffect(() => {
    if (scriptId) {
      loadVersions()
    }
  }, [scriptId])

  // 渲染主内容
  const renderMainContent = () => {
    if (loading) {
      return (
        <div style={{ 
          display: 'flex', 
          justifyContent: 'center', 
          alignItems: 'center', 
          height: 400 
        }}>
          <Spin size="large" />
        </div>
      )
    }

    switch (viewMode) {
      case 'compare':
        return compareVersions ? (
          <VersionCompare
            version1={compareVersions[0]}
            version2={compareVersions[1]}
            onSwapVersions={handleSwapCompareVersions}
            onClose={handleBackToHistory}
          />
        ) : null

      case 'detail':
        return selectedVersion ? (
          <VersionDetail
            version={selectedVersion}
            isCurrentVersion={selectedVersion.id === currentVersion?.id}
            onRevert={handleVersionRevert}
            onDelete={handleVersionDelete}
            onComment={handleVersionComment}
            onClose={handleBackToHistory}
          />
        ) : null

      case 'history':
      default:
        return (
          <VersionHistory
            scriptId={scriptId}
            versions={versions}
            loading={loading}
            currentVersionId={currentVersion?.id}
            onVersionSelect={handleVersionSelect}
            onVersionCompare={handleVersionCompare}
            onVersionRevert={handleVersionRevert}
            onVersionDelete={handleVersionDelete}
            onVersionComment={handleVersionComment}
            showActions={true}
            maxHeight={600}
          />
        )
    }
  }

  // 渲染工具栏
  const renderToolbar = () => (
    <div style={{ 
      padding: '12px 16px',
      borderBottom: '1px solid #f0f0f0',
      background: '#fafafa',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Space>
          <HistoryOutlined />
          <Title level={4} style={{ margin: 0 }}>版本管理</Title>
          {versions.length > 0 && (
            <span style={{ color: '#666', fontSize: 12 }}>
              共 {versions.length} 个版本
            </span>
          )}
        </Space>

        <Space>
          {viewMode !== 'history' && (
            <Button onClick={handleBackToHistory}>
              返回历史
            </Button>
          )}
          
          {showCreateVersion && (
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleCreateVersion}
            >
              创建版本
            </Button>
          )}
        </Space>
      </div>
    </div>
  )

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* 工具栏 */}
      {renderToolbar()}

      {/* 主内容 */}
      <div style={{ flex: 1, padding: 16, overflow: 'auto' }}>
        {renderMainContent()}
      </div>
    </div>
  )
}

export default VersionManager